package com.gitee.wsl.lifecycle.context

import com.gitee.wsl.data.state.statekeeper.StateKeeper
import com.gitee.wsl.data.state.statekeeper.StateKeeperDispatcher
import com.gitee.wsl.data.state.statekeeper.StateKeeperOwner
import com.gitee.wsl.lifecycle.Lifecycle
import com.gitee.wsl.lifecycle.LifecycleOwner

/**
 * A generic component context that extends [LifecycleOwner], [StateKeeperOwner],
 * [InstanceKeeperOwner] and [BackHandlerOwner] interfaces, and also able to create
 * new instances of itself via [ComponentContextFactory].
 */
interface GenericComponentContext<out T : Any> :
    LifecycleOwner,
    StateKeeperOwner,
    ComponentContextFactoryOwner<T>

/**
 * A default component context interface provided by Decompose.
 * Should be passed to component classes via their constructors to
 * enable features like lifecycle handling, state preservation, navigation,
 * etc.
 *
 * It is also possible to define your own interface with additional
 * properties or methods, and use that instead of this one.
 */
interface ComponentContext : GenericComponentContext<ComponentContext>

/**
 * A default implementation of the [ComponentContext] interface.
 * Can be also used in tests.
 */
class DefaultComponentContext(
    override val lifecycle: Lifecycle,
    stateKeeper: StateKeeper? = null,
    ) : ComponentContext {

    override val stateKeeper: StateKeeper = stateKeeper ?: StateKeeperDispatcher()
    //override val instanceKeeper: InstanceKeeper = instanceKeeper ?: InstanceKeeperDispatcher().attachTo(lifecycle)
    //override val backHandler: BackHandler = backHandler ?: BackDispatcher()
    override val componentContextFactory: ComponentContextFactory<ComponentContext> = ComponentContextFactory(::DefaultComponentContext)

    constructor(lifecycle: Lifecycle) : this(
        lifecycle = lifecycle,
        stateKeeper = null,
    )
}